<?php

class baRecountTask extends sfBaseTask
{
  protected function configure()
  {
    // // add your own arguments here
    // $this->addArguments(array(
    //   new sfCommandArgument('my_arg', sfCommandArgument::REQUIRED, 'My argument'),
    // ));

    $this->addOptions(array(
      new sfCommandOption('application', null, sfCommandOption::PARAMETER_REQUIRED, 'The application name','ba'),
      new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev'),
      new sfCommandOption('connection', null, sfCommandOption::PARAMETER_REQUIRED, 'The connection name', 'propel'),
      // add your own options here
    ));

    $this->namespace        = 'ba';
    $this->name             = 'recount';
    $this->briefDescription = '';
    $this->detailedDescription = <<<EOF
The [ba:recount|INFO] task does things.
Call it with:

  [php symfony ba:recount|INFO]
EOF;
  }

  protected function execute($arguments = array(), $options = array())
  {
    // initialize the database connection
    $databaseManager = new sfDatabaseManager($this->configuration);
    $connection = $databaseManager->getDatabase($options['connection'] ? $options['connection'] : null)->getConnection();
    $this->context = sfContext::createInstance($this->configuration);
    $this->context->getConfiguration()->loadHelpers('I18N');
    
    //sfProjectConfiguration::getActive()->loadHelpers('I18N');
    //include(sfConfig::get('sf_plugins_dir').'/sfDateTime2Plugin/lib/sfDate.class.php');
    
    // add your code here
    
  //  $sql = "select id from sf_guard_user";
   // $rez=mysql_query($sql);
   // while(list($user_id)=mysql_fetch_row($rez))
  //  {
   //   echo $user_id;
   // }
   
   $now = new sfDate();
    
   $c = new Criteria();
   $c->add(sfGuardUserPeer::IS_OTPUSK,false);
   $c->add(sfGuardUserPeer::IS_ACTIVE,true);
   $c->add(sfGuardUserPeer::GENDER,'m');
   $c->add(sfGuardUserPeer::IS_ABON,true);
   
   $users = sfGuardUserPeer::doSelect($c);
   foreach($users as $u)
   {
     ////Отнимаем стоимость абонплаты в конце 
     if($u->getDateExpireAbon()<date('Y-m-d'))
     {

   	   					     $pa = new Payment();
							 $pa->setUserId( $u->getId());
							 $pa->setPaymentId( $u->getId());
							 $pa->setLevelId(11);
							 $pa->setSumma( $u->getAccount());
							 $pa->setDirection(0);
							 $pa->save();
	   $u->setAccount(0);
   	   $u->save();
     }
   	 ////
   	 
   	 //Проверка истечения абонемента
   	 if($now->addDay(10)->dump()>$u->getDateExpireAbon())
   	 {
   	 	     //// Шлем уведомление о окончании абонемента	
		      $not=MailnoticePeer::retrieveByPK(7);    
		      $title = $not->getTitle($u->getLanguage());
		      $body=$not->parse_body(array(
		          '%date%'=>$u->getDateExpireAbon()
		      ),$u->getLanguage());		      
		      myTools::sendMail($u->getEmail(),$title,$body);	
		      ///// 		      
		      
   	 }
   	 
      	 if($now->addDay(10)->dump()>$u->getDateExpireOtpusk())
   	 {
   	 	     //// Шлем уведомление о окончании абонемента	
		      $not=MailnoticePeer::retrieveByPK(5);    
		      $title = $not->getTitle($u->getLanguage());
		      $body=$not->parse_body(array(
		          '%date%'=>$u->getDateExpireOtpusk()
		      ),$u->getLanguage());		      
		      myTools::sendMail($u->getEmail(),$title,$body);	
		      ///// 		      
		      
   	 } 	 
   	 
   	 
   	 ////Окончание баланса
       	 if($u->getAccount()<=0)
   	 {
   	 	     //// Шлем уведомление о окончании счета	
		      $not=MailnoticePeer::retrieveByPK(8);    
		      $title = $not->getTitle($u->getLanguage());
		      $body=$not->getBody($u->getLanguage());      
		      myTools::sendMail($u->getEmail(),$title,$body);	
		      ///// 		      
		      
   	 }

      	 ////Окончание галереи
       	
   	   $gallerys = $u->getGroupgallerys();
   	   foreach($gallerys as  $g)
   	   {
   	    if($now->addDay(10)->dump()>$g->getDateExpire())
	   	 {
	   	 	     //// Шлем уведомление о окончании счета	
			      $not=MailnoticePeer::retrieveByPK(10);    
			      $title = $not->getTitle($u->getLanguage());
			      $body=$not->parse_body(array(
			          '%date%'=>$g->getDateExpire()
			      ),$u->getLanguage());
			      myTools::sendMail($u->getEmail(),$title,$body);	
			      ///// 		      
			      
	   	 }
   	   }

   	   
   	   
   	    ///Уведомление о днях рождения фаворитов
      
		   $favs = $u->getFavoritesRelatedByUserId();
		   if($favs){
		   	
		   	foreach($favs as $f)
		   	{
		   		$us = $f->getsfGuardUserRelatedByFavId();
		   		$dt = new sfDate($us->getBirthday());
		   		
		   		$dn = $dt->subtractDay(10)->addYear($us->getAge())->format('Y-m-d');
		   		
		   		//echo '|'.$us.'-'.$dn.'='.date('Y-m-d').'|';

		   		if($dn== date('Y-m-d'))
		   		{
		   	    ////Создаем новость
				$n = new Material();
				$n->setUserId($us->getId());				
				$n->setIShortDescription(sfContext::getInstance()->getI18N()->__('У пользователя через 10 дней день рожденья'),'ru');
				$n->setIShortDescription(sfContext::getInstance()->getI18N()->__('User has birthday after 10 days'),'en');
				$n->setTypeId(10);
				$n->setPub(true);
				$n->save();
				
				///
		   		}
		   		
		   		////Бежим по детям
		   		$chl = $us->getChilds();
		   		if($chl)
		   		{
		   			foreach($chl as $ch)
		   			{
		   				$dt = new sfDate($ch->getBirthday());
		   				$dn = $dt->subtractDay(10)->addYear($ch->getAge())->format('Y-m-d');
		   					   		if($dn== date('Y-m-d'))
							   		{
							   	    ////Создаем новость
									$n = new Material();
									$n->setUserId($us->getId());				
									$n->setIShortDescription(sfContext::getInstance()->getI18N()->__('У ребенка пользователя через 10 дней день рожденья'),'ru');
									$n->setIShortDescription(sfContext::getInstance()->getI18N()->__('User`s child has birthday after 10 days'),'en');
									$n->setTypeId(10);
									$n->setPub(true);
									$n->save();
									
									///
							   		}
		   			}
		   		}
		   		
		   	
		   		//$dt = date("Y-m-d", mktime(0,0,0,date("m",$tm),date("d",$tm)-10,date("y")));
		   	}
		   	
		   }
		   ///
   	   

   	   
   	 echo $u->getId(); 
   }
    
   
   ////Удаляем устаревшие сообщения
   $now = new sfDate();
   $c1 = new Criteria();
   $c1->add(MailboxPeer::CREATED_AT,$now->subtractDay(60)->dump(),Criteria::LESS_THAN);
   $ma = MailboxPeer::doSelect($c1);
   foreach($ma as $m)
   {
   	$m->delete();
   }
   ///

   
   
   
   
   
   
  }
  
	
  
}
